<?php

namespace App\Service\Message\v1_2_7;

use App\Constants\ErrorCode;
use App\Helpers\ConfigUtil;
use App\Model\CoinLog;
use App\Model\Message;
use App\Model\ProfileVerifyLog;
use App\Model\Service\ConsumeService;
use App\Model\UserCoin;
use App\Model\UserProfile;
use App\Model\WechatCheckApply;
use App\Service\User\UserBaseService;
use Exception;
use Hyperf\DbConnection\Db;

/**
 * 微信申请操作
 */
class WechatApplyOpService extends UserBaseService
{
    protected function RoVerifyList()
    {
        return [
            'apply_user_id' => 'required|int',
        ];
    }

    public function handle()
    {
        $userId = $this->getUserId();
        //申请用户ID
        $applyUserId = $this->request->input('apply_user_id', 0);
        //消息ID
        $msgId = $this->request->input('im_msg_id', '');
        //消息时间
        $msgTime = $this->request->input('im_msg_time', 0);
        //操作：1-同意，0-不同意
        $option = intval($this->request->input('op', 1));
        //查询操作记录
        $applyLog = WechatCheckApply::checkLog($applyUserId, $userId);
        if (!$applyLog) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '该申请记录不存在～');
        }

        if ($applyLog->status != WechatCheckApply::APPLY_ING) {
            return $this->setError(ErrorCode::PARAMETER_ERROR, '该申请记录已无法操作～');
        }

        $expTime = 24 * 3600;
        if (strtotime($applyLog->created_at) < (time() - $expTime)) {
            WechatCheckApply::expireLog($applyLog->id);
            return $this->setError(ErrorCode::WECHAT_APPLY_EXP, '该申请记录已过期无法操作');
        }

        //同意
        if ($option == 1) {
            //是否认证微信
            $checkWechat = ProfileVerifyLog::checkVerified($userId, ProfileVerifyLog::TYPE_WECHAT, 'data');
            //没提交认证，或者审核不通过
            if (!$checkWechat || in_array($checkWechat->status, [ProfileVerifyLog::STATUS_BAD])) {
                return $this->setError(ErrorCode::WECHAT_NOT_SUBMIT, '请先进行微信认证～');
            }
            //正在审核中
            elseif ($checkWechat->status == ProfileVerifyLog::STATUS_ING) {
                return $this->setError(ErrorCode::WECHAT_NOT_PASS, '您提交的微信尚未通过审核，请添加客服微信进行认证～');
            }
        }

        //对方支付的流水记录
        $payLog = CoinLog::checkConsumeFrom($applyUserId, $userId, CoinLog::FROM_CHECK_WECHAT_OUT);
        if (!$payLog) {
            return $this->setError(ErrorCode::WECHAT_APPLY_NOT_PAY, '对方未支付查看微信的金币，暂无法操作～');
        }

        Db::beginTransaction();
        try {
            //更新申请记录状态
            WechatCheckApply::updateResult($applyLog->id, $option);

            //同意接收金币
            if ($option == 1) {
                $incomeCoin = round($payLog->coin * (1 - ConfigUtil::getConsumeRate($userId)), 1);
                ConsumeService::gainIncome(
                    $userId,
                    $incomeCoin,
                    CoinLog::FROM_CHECK_WECHAT_IN,
                    $applyUserId
                );
            }
            //拒绝退回金币
            else {
                ConsumeService::gainIncome(
                    $applyUserId,
                    $payLog->coin,
                    CoinLog::FROM_CHECK_WECHAT_BACK,
                    $userId
                );
            }
            Db::commit();
        } catch (\Throwable $exception) {
            log_info(__METHOD__ . '==Exception:' . $exception->getMessage());
            Db::rollBack();
        }

        //站内信通知申请者
        $profile = UserProfile::getProfile($userId);
        Message::pushWechatResult($applyUserId, $option, ['host_name' => $profile->nick_name]);

        //消息撤回
        Message::recallWechatApply($userId, $msgId, $msgTime);
        //发送新消息
        $applyProfile = UserProfile::getProfile($applyUserId);
        Message::pushWechatApply($userId, [
            'nick_name' => $applyProfile->nick_name,
            'user_id' => $applyProfile->user_id,
        ], $option == 1 ? 'ok' : 'refuse');

        //操作结果
        return ['result' => 1];
    }
}
